package com.ipay.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ipay.entity.CashiersEntity;
import com.ipay.entity.MerchantInfoEntity;
import com.ipay.entity.PayChannelEntity;
import com.ipay.entity.QRCodeEntity;
import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.service.CashiersService;
import com.ipay.service.MerchantInfoService;
import com.ipay.service.QRCodeService;
import com.ipay.utils.Constant;
import com.ipay.utils.DateUtils;
import com.ipay.utils.HttpUtils;
import com.ipay.utils.PageUtils;
import com.ipay.utils.Query;
import com.ipay.utils.R;
import com.ipay.utils.RandomStringUtils;
import com.ipay.validator.ValidatorUtils;
import com.ipay.validator.group.AddGroup;

/**
 * 支付渠道商管理
 * 
 * @author Luohx
 */
@Transactional
@Controller
@RequestMapping("/cashiers")
public class CashiersController extends AbstractController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private CashiersService cashiersService;
	@Autowired
	private JedisExecutor jedisManager;
	@Autowired
	private MerchantInfoService merchantInfoService;
	@Autowired
	private QRCodeService qrCodeService;

	@RequestMapping("/{url}.html")
	public String page(@PathVariable("url") String url) {
		return "cashiers/" + url + ".html";
	}
	
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@ResponseBody
	@RequiresPermissions("cashiers:list")
	public R list(@RequestParam Map<String, Object> params,HttpServletRequest request) {
		logger.info("params==" + params.toString());
		
		String merchantNo = getUser().getMerchantNo();
		String userType = getUser().getUserType();
		if(userType.equals("2")){
			if(merchantNo != null){
				params.put("merchantNo", merchantNo);
				//params.put("role", 2);
			}else{
				return R.error("参数异常，请联系管理员");
			}
		}
		//params.put("deleteStatus", "2");
		// 查询列表数据
		Query query = new Query(params);
		logger.info("query==" + query.toString());
		List<CashiersEntity> cashiersList = cashiersService.queryList(query);
		int total = cashiersService.queryTotal(query);
		logger.info("total==" + total);
		PageUtils pageUtil = new PageUtils(cashiersList, total, query.getLimit(), query.getPage());
		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@ResponseBody
	@RequiresPermissions("cashiers:save")
	public R save(@RequestBody CashiersEntity cashiers,HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("mobilePhone", cashiers.getMobilePhone());
		map.put("deleteStatus", 2);
		List<CashiersEntity> list = cashiersService.queryList(map);
		if(list.size() > 0){
			return R.error("手机号已有关联用户");
		}
		String mobile = cashiers.getMobilePhone();
		String inviteCode = RandomStringUtils.randomNumeric(6);
		//根据商户id查询商户信息
		String merchantNo = getUser().getMerchantNo();
		String userType = getUser().getUserType();
		MerchantInfoEntity merchantInfo = new MerchantInfoEntity();
		merchantInfo.setMerchantNo(cashiers.getMerchantId());
		MerchantInfoEntity merchant2 = merchantInfoService.queryByParams(merchantInfo);
		try {
	        if (merchant2 != null) {
	            
	            Map<String, String> msgMap = new HashMap<String,String>();
	            if(merchantNo != null && userType.equals(Constant.USER_TYPE_SH)){
	            	merchantInfo.setMerchantNo(merchantNo);
	            	MerchantInfoEntity merchant = merchantInfoService.queryByParams(merchantInfo);
	            	msgMap.put("merchant", merchant.getUsername());
	            }else{
	            	msgMap.put("merchant", "系统管理员");
	            }
	            msgMap.put("shop", merchant2.getShopName());
	            msgMap.put("mobile", mobile);
	            msgMap.put("code", inviteCode);
	            
	            cashiers.setInviteCode(inviteCode);
        		cashiersService.save(cashiers);
	            
	            JSONObject object = HttpUtils.getValidCode(mobile, "37717", msgMap);
	            
	            logger.info("发送短信验证码返回结果：" + object);
	            if (object.getInt("error_code") == 0) { // 发送成功
	        		return R.ok("邀请码已发送至该收款员手机，请通知尽快使用");
	            } else {
	                return R.error("邀请码发送失败");
	            }
	        }else{
	        	 return R.error(502, "商户信息错误");
	        }
		} catch (Exception e) {
            e.printStackTrace();
            return R.error(502, "增加收款员失败");
        }
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@ResponseBody
	@RequiresPermissions("cashiers:update")
	public R update(@RequestBody CashiersEntity cashiers,HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
 		map.put("mobilePhone", cashiers.getMobilePhone());
		map.put("deleteStatus", Constant.ActivateState.T_DELETED.getValue());
		List<CashiersEntity> list = cashiersService.queryList(map);
		if(list.size() > 0 && list.get(0).getId().longValue() != cashiers.getId().longValue()){
			return R.error("手机号已关联用户");
		}
		if(cashiersService.update(cashiers) > 0){
			return R.ok("修改成功");
		}
		return R.error(502, "修改失败");
	}
	
	
	/**
	 * 信息
	 * @throws IOException 
	 */
	@RequestMapping("/info/{id}")
	@ResponseBody
	@RequiresPermissions("cashiers:info")
	public R info(@PathVariable("id") Long id,HttpServletRequest request, HttpServletResponse response) throws IOException {
		CashiersEntity cashiers = cashiersService.queryObject(id);
		return R.ok().put("cashiers", cashiers);
	}

	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	@RequiresPermissions("cashiers:delete")
	public R delete(@RequestBody Long[] ids) {
		cashiersService.updateBatch(ids);
		return R.ok();
	}
	
	/**
	 * 恢复已删除的收款员为正常状态
	 */
	@RequestMapping("/recovery")
	@ResponseBody
	@RequiresPermissions("cashiers:recovery")
	public R recovery(@RequestBody Long[] ids) {
		cashiersService.recoveryBatch(ids);
		return R.ok();
	}
	
	
	
	/**
	 * 查询收款员二维码列表
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getCodeList", method = RequestMethod.GET)
	public ModelAndView getCodeList(String userId,HttpServletRequest request) {
		//根据商户id查询 二维码表
		List<QRCodeEntity>	list = 	qrCodeService.findListByUserId(userId);
		if(list.size() > 0){
			for(QRCodeEntity code : list){
				code.setSaveUrl("/merchantinfo/lookqrCode?codeNo="+code.getCodeNo());
				//code.setSaveUrl("http://localhost:8080/merchantinfo/lookqrCode?codeNo="+code.getCodeNo());
			}
		}   
		return new ModelAndView("/merchant/codeList.jsp").addObject("codeList", list);
	}
}
